package com.wanxi.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.wanxi.dto.ResultDTO;
import com.wanxi.model.UserModel;
import com.wanxi.service.UserService;
import com.wanxi.service.impl.UserServiceImpl;
import com.wanxi.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/back/user/findAll")
public class UserFindAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        1.乱码处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        2.得到前端的值
        String username = req.getParameter("username");
        String sex = req.getParameter("sex");
        String phone = req.getParameter("phone");
        String birthday = req.getParameter("birthday");
        String startBirthday = req.getParameter("startBirthday");
        String endBirthday = req.getParameter("endBirthday");
        String email = req.getParameter("email");
        String address = req.getParameter("address");
        String hobby = req.getParameter("hobby");
        String enable = req.getParameter("enable");
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
//        3.封装到model
        UserModel model = UserModel.builder()
                .name(Tool.nullToStr(username))
                .sex(Tool.nullToStr(sex))
                .phone(Tool.nullToStr(phone))
                .hobby(Tool.nullToStr(hobby))
                .address(Tool.nullToStr(address))
                .birthday(Tool.nullToDate(birthday))
                .startBirthday(Tool.nullToDate(startBirthday))
                .endBirthday(Tool.nullToDate(endBirthday))
                .email(Tool.nullToStr(email))
                .enable(Tool.nullToInt(enable))
                .page(Tool.nullToPage(page))
                .limit(Tool.nullToLimit(limit))
                .build();
//        4.调用服务逻辑层
        UserService userService = new UserServiceImpl();
        ResultDTO resultDTO = userService.findAll(model);
//        5.将结果返回给前端
//        以后返回给前端永远是对象：而且是json对象，所以需要将数据强制转换为json对象
//        将数据转换为json对象有很多种方式，fastjson
        resp.getWriter().println(JSONObject.toJSONString(resultDTO));

    }
}
